package com.usoft;

import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import akka.dispatch.Mapper;
import akka.dispatch.OnComplete;
import akka.dispatch.OnFailure;
import akka.dispatch.OnSuccess;
import scala.concurrent.ExecutionContextExecutorService;
import scala.concurrent.Future;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 * Created by liyanxin on 2015/1/8.
 */
public class FutureDemo2 {

    public static void main(String args[]) {

        final ExecutionContextExecutorService ec = ExecutionContexts.
                fromExecutorService(Executors.newCachedThreadPool());

        Future<String> f1 = Futures.future(new Callable<String>() {
            public String call() throws InterruptedException {
                Thread.sleep(5000); //在当前的线程内阻塞5秒
                System.out.println(Thread.currentThread().getName() + " thread end|||f1");
                return "Hello" + "World";
            }
        }, ec);


        /**
         * flatMap  f1->f2
         */
        Future<Integer> f2 = f1.flatMap(new Mapper<String, Future<Integer>>() {
            public Future<Integer> apply(final String s) {
                return Futures.future(new Callable<Integer>() {
                    public Integer call() {
                        return s.length();
                    }
                }, ec);
            }
        }, ec);

        f2.onComplete(new OnComplete<Integer>() {
            @Override
            public void onComplete(Throwable failure, Integer success) throws Throwable {
                System.out.print(Thread.currentThread().getName() + " thread end|||");
                System.out.println("f2 on complete=" + success);
            }
        }, ec);

        f2.onSuccess(new OnSuccess<Integer>() {
            @Override
            public void onSuccess(Integer result) throws Throwable {
                System.out.print(Thread.currentThread().getName() + " thread end|||");
                System.out.println("返回结果的长度=" + result);
            }
        }, ec);

        f2.onFailure(new OnFailure() {
            @Override
            public void onFailure(Throwable failure) throws Throwable {
                System.out.print(Thread.currentThread().getName() + " thread end|||");
                System.out.println("f2 failure=" + failure.getMessage());
            }
        }, ec);
        System.out.println(Thread.currentThread().getName() + " thread end");
    }
}
